//
//  YDUserDataManager.swift
//  YDPerfectServer
//
//  Created by rowena on 2019/8/5.
//

/**
 * 用户数据管理
 */

import Foundation

class YDUserDataManager  {

    /**
     * 用户管理 之 登录
     * @pram parameters 请求登录时传递的参数
     *
     * @return 返回登录回调的JSON字符串
     */
    func userDataManagerWithLogin(parameters: [String: Any]) -> String {
        
        //获取参数 用户名
        let userName: String = parameters["user_name"] as! String
        //获取参数 用户密码
        let userPassword: String = parameters["user_password"] as! String
        let userDatabase: YDUserDatabase = YDUserDatabase()
    
        let user_token: String = userDatabase.selectUserData(userName: userName, userPassword: userPassword)
        if user_token.count > 0 {
            let jsonDic = ["token": user_token]
            return YDDataFormatManager.baseResponseBodyJSONData(code: 0, message: "登录成功", data: jsonDic)
        }
        return YDDataFormatManager.baseResponseBodyJSONData(code: 1, message: "账号或密码错误", data: nil)
    }
    
    /**
     * 用户管理 之 注册
     * @pram parameters 请求登录时传递的参数
     *
     * @return 返回登录回调的JSON字符串R
     */
    func userDataManagerWithRegister(parameters: [String: Any]) -> String {
        
        //获取参数 用户名
        let userName: String = parameters["user_name"] as! String
        //获取参数 用户密码
        let userPassword: String = parameters["user_password"] as! String
        
        let uuidString: String = UUID.init().uuidString
        
        let userToken: String = String(uuidString.prefix(32))
        let date = Date()
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        let userTime = dateFormatter.string(from: date)
        let userDatabase: YDUserDatabase = YDUserDatabase()
        
        var jsonString = YDDataFormatManager.baseResponseBodyJSONData(code: 1, message: "账号或密码错误", data: ["user_token": userToken, "user_time": userTime])
        
        
        switch userDatabase.insertUserData(userName: userName, userPassword: userPassword, userToken: userToken, userTime: userTime) {
            
        case YDUserRegister.Success:
            jsonString = YDDataFormatManager.baseResponseBodyJSONData(code: 0, message: "注册成功", data: ["user_token": userToken, "register_time": userTime])
            break
        case YDUserRegister.Failure:
            jsonString = YDDataFormatManager.baseResponseBodyJSONData(code: 1, message: "注册失败", data: nil)
            break
        case YDUserRegister.Exist:
            jsonString = YDDataFormatManager.baseResponseBodyJSONData(code: 2, message: "该账号已注册", data: nil)
            break
        }
        
        return jsonString
    }
}
